import 'package:flutter/material.dart';
import 'dart:math' as math;
import '../../models/airplane_model.dart';
import '../../widgets/status_panel.dart';

class VoiceControlScreen extends StatefulWidget {
  final AirplaneModel model;

  const VoiceControlScreen({super.key, required this.model});

  @override
  State<VoiceControlScreen> createState() => _VoiceControlScreenState();
}

class _VoiceControlScreenState extends State<VoiceControlScreen> {
  bool _isListening = false;
  String _lastCommand = '';
  String _status = '准备就绪';
  double _altitude = 0.0;
  double _speed = 0.0;
  bool _isFlying = false;
  List<String> _commandHistory = [];

  // 可用的语音命令列表
  final List<String> _availableCommands = [
    '启动',
    '起飞',
    '降落',
    '停止',
    '左转',
    '右转',
    '上升',
    '下降',
    '加速',
    '减速',
    '悬停',
    '返航',
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('语音控制模式'),
        actions: [
          IconButton(
            icon: const Icon(Icons.info_outline),
            onPressed: _showHelp,
          ),
        ],
      ),
      body: Column(
        children: [
          // StatusPanel(
          //   model: widget.model,
          //   batteryLevel: 78,
          //   signalStrength: 85,
          //   altitude: _altitude,
          //   speed: _speed,
          // ),
          // 语音识别状态
          // Container(
          //   padding: const EdgeInsets.all(16.0),
          //   color:
          //       _isListening
          //           ? Colors.green.withOpacity(0.2)
          //           : Colors.grey.withOpacity(0.2),
          //   child: Row(
          //     children: [
          //       Icon(
          //         _isListening ? Icons.mic : Icons.mic_off,
          //         color: _isListening ? Colors.green : Colors.grey,
          //         size: 32,
          //       ),
          //       const SizedBox(width: 16),
          //       Expanded(
          //         child: Column(
          //           crossAxisAlignment: CrossAxisAlignment.start,
          //           children: [
          //             Text(
          //               _isListening ? '正在聆听...' : '点击麦克风开始聆听',
          //               style: TextStyle(
          //                 fontWeight: FontWeight.bold,
          //                 color:
          //                     _isListening
          //                         ? Colors.green
          //                         : Colors.grey.shade700,
          //               ),
          //             ),
          //             if (_lastCommand.isNotEmpty)
          //               Text(
          //                 '上次命令: $_lastCommand',
          //                 style: const TextStyle(fontStyle: FontStyle.italic),
          //               ),
          //           ],
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
          // 飞行状态
          // Container(
          //   padding: const EdgeInsets.all(12.0),
          //   color:
          //       _isFlying
          //           ? Colors.blue.withOpacity(0.1)
          //           : Colors.grey.withOpacity(0.1),
          //   child: Row(
          //     mainAxisAlignment: MainAxisAlignment.center,
          //     children: [
          //       Icon(
          //         _isFlying ? Icons.flight_takeoff : Icons.flight_land,
          //         color: _isFlying ? Colors.blue : Colors.grey,
          //       ),
          //       const SizedBox(width: 8),
          //       Text(
          //         '状态: $_status',
          //         style: TextStyle(
          //           fontWeight: FontWeight.bold,
          //           color: _isFlying ? Colors.blue : Colors.grey.shade700,
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
          // 命令历史记录
          // Expanded(
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     children: [
          //       Padding(
          //         padding: const EdgeInsets.all(16.0),
          //         child: Text(
          //           '命令历史',
          //           style: Theme.of(context).textTheme.titleMedium,
          //         ),
          //       ),
          //       Expanded(
          //         child:
          //             _commandHistory.isEmpty
          //                 ? const Center(child: Text('尚无命令历史记录'))
          //                 : ListView.builder(
          //                   itemCount: _commandHistory.length,
          //                   itemBuilder: (context, index) {
          //                     final command = _commandHistory[index];
          //                     return ListTile(
          //                       leading: const Icon(Icons.history),
          //                       title: Text(command),
          //                       dense: true,
          //                     );
          //                   },
          //                 ),
          //       ),
          //     ],
          //   ),
          // ),
          // 可用命令列表
          Container(
            padding: const EdgeInsets.all(16.0),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surfaceVariant,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(16),
                topRight: Radius.circular(16),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('可用命令', style: Theme.of(context).textTheme.titleMedium),
                const SizedBox(height: 8),
                Wrap(
                  spacing: 8,
                  runSpacing: 8,
                  children:
                      _availableCommands.map((command) {
                        return Chip(
                          label: Text(command),
                          backgroundColor:
                              Theme.of(context).colorScheme.primaryContainer,
                          labelStyle: TextStyle(
                            color:
                                Theme.of(
                                  context,
                                ).colorScheme.onPrimaryContainer,
                          ),
                        );
                      }).toList(),
                ),
              ],
            ),
          ),
          // 控制按钮
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: _toggleListening,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _isListening ? Colors.red : Colors.green,
                      foregroundColor: Colors.white,
                      minimumSize: const Size(double.infinity, 50),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(_isListening ? Icons.mic_off : Icons.mic),
                        const SizedBox(width: 8),
                        Text(_isListening ? '停止聆听' : '开始聆听'),
                      ],
                    ),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _emergencyStop,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      foregroundColor: Colors.white,
                      minimumSize: const Size(double.infinity, 50),
                    ),
                    child: const Text('紧急停止'),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _toggleListening() {
    setState(() {
      _isListening = !_isListening;
      if (_isListening) {
        _simulateVoiceRecognition();
      }
    });
  }

  void _simulateVoiceRecognition() {
    // 模拟语音识别过程
    Future.delayed(const Duration(seconds: 3), () {
      if (mounted && _isListening) {
        // 随机选择一个命令
        final command =
            _availableCommands[DateTime.now().second %
                _availableCommands.length];
        _processCommand(command);
      }
    });
  }

  void _processCommand(String command) {
    setState(() {
      _lastCommand = command;
      _commandHistory.insert(
        0,
        '${DateTime.now().hour}:${DateTime.now().minute}:${DateTime.now().second} - $command',
      );

      // 处理命令
      switch (command) {
        case '启动':
        case '起飞':
          _isFlying = true;
          _status = '飞行中';
          _altitude = 20.0;
          _speed = 5.0;
          break;
        case '降落':
        case '停止':
          _isFlying = false;
          _status = '已降落';
          _altitude = 0.0;
          _speed = 0.0;
          break;
        case '左转':
          _status = '向左转';
          break;
        case '右转':
          _status = '向右转';
          break;
        case '上升':
          _altitude += 10.0;
          _status = '上升中';
          break;
        case '下降':
          _altitude = math.max(0, _altitude - 10.0);
          _status = '下降中';
          break;
        case '加速':
          _speed += 2.0;
          _status = '加速中';
          break;
        case '减速':
          _speed = math.max(0, _speed - 2.0);
          _status = '减速中';
          break;
        case '悬停':
          _status = '悬停中';
          _speed = 0.0;
          break;
        case '返航':
          _status = '返航中';
          break;
      }
    });

    // 如果仍在聆听，继续模拟语音识别
    if (_isListening) {
      _simulateVoiceRecognition();
    }
  }

  void _emergencyStop() {
    setState(() {
      _isListening = false;
      _isFlying = false;
      _status = '紧急停止';
      _altitude = 0.0;
      _speed = 0.0;
    });

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('紧急停止'),
            content: const Text('已启动紧急停止程序，飞机将安全降落。'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('确认'),
              ),
            ],
          ),
    );
  }

  void _showHelp() {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('语音控制帮助'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text('使用以下语音命令控制飞机:'),
                const SizedBox(height: 8),
                ...[
                  '启动/起飞',
                  '降落/停止',
                  '左转/右转',
                  '上升/下降',
                  '加速/减速',
                  '悬停',
                  '返航',
                ].map(
                  (cmd) => Padding(
                    padding: const EdgeInsets.symmetric(vertical: 4.0),
                    child: Text('• $cmd'),
                  ),
                ),
                const SizedBox(height: 16),
                const Text('点击麦克风按钮开始聆听命令'),
                const Text('紧急情况下，请使用"紧急停止"按钮'),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('了解'),
              ),
            ],
          ),
    );
  }
}
